package com.example.project_01.service.impl;

import com.example.project_01.commons.Result;
import com.example.project_01.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Stack;
import java.util.UUID;

@Service
//将文件下载到本地
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${upload.path}")
    private String uploadPath;    //注入上传目录路径

    @Value("${server.port}")
    private int serverPort;   //获取服务端口

    @Override
    public Result uploadImg(MultipartFile file) {
        String fileName = null;
        try {
            //生成唯一文件名(随机UUID+源文件名拼接)
            fileName = UUID.randomUUID() + file.getOriginalFilename();

            //构建完整文件路径
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();   //创建目录，包括父目录
            }

            //
            File targetFile = new File(uploadPath , fileName);

            //保存文件
            Files.copy(file.getInputStream(),targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            //构建访问url
            String url = "http://localhost:" + serverPort + "/image/" + fileName;

            return new Result(200,"图片上传成功",url);

        } catch (IOException e) {
            System.out.println("图片上传失败" + e.getMessage());
            //打印详细信息
            e.printStackTrace();
            return new Result(201,"图片上传失败");
        }

    }

}
